package JackSu.aobing;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;

/**
 * MapTest
 *
 * @author Syzer
 * @Description
 * @Date 2021/7/2 16:02
 */
public class MapTest {

    public static void main(String[] args) {
        printEmptyCapacityMap();
    }

    public static void printEmptyCapacityMap() {
        HashMap<String, String> map = new HashMap<>(4);
        System.out.println(
                "empty 初始化长度：" + getCapacity(map));

        map.put("11", "22");
        map.put("12", "22");
        map.put("13", "22");
        System.out.println(
                "empty put 之后 长度：" + getCapacity(map));
    }

    public static Object getCapacityMethod(HashMap<?, ?> hashMap) {
        try {
            // 获取 table 字段
            Method capacity = hashMap.getClass().getDeclaredMethod("capacity");
            // 开启访问权限
            capacity.setAccessible(true);
            //返回当前ArrayList实例的容量值
            return capacity.invoke(hashMap);
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
    }

    public static int getCapacity(HashMap<?, ?> hashMap) {
        Class<HashMap> hashMapClass = HashMap.class;
        try {
            // 获取 table 字段
            Field field = hashMapClass.getDeclaredField("table");
            // 开启访问权限
            field.setAccessible(true);
            // 把示例传入get，获取实例字段table的值
            Object[] objects = (Object[]) field.get(hashMap);
            //返回当前ArrayList实例的容量值
            return objects.length;
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
    }
}
